#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@desc: .

@Project ：kuberCloudTest
@File ：mirrors.py
@Author ：admin
@Date ：2024/3/21 13:52 
"""
from kuberCloudTest.cloud_resources.urls import CloudResourcesUrls
from kuberCloudTest.common.basic import basicUtils
from kuberCloudTest.common.constant import OFFSET, LIMIT, AsyncType
from kuberCloudTest.common.utils import _getDetail, _getOperationType
from kuberCloudTest.exception import KuberCloudException


class mirrorUtils(basicUtils):

    def __init__(self, accessToken):
        super().__init__(accessToken)


def get_utils(accessToken):
    return mirrorUtils(accessToken=accessToken)


def getMirror(accessToken, mirrorId=None, **kwargs):
    """
    获取镜像列表
    :param mirrorId: 镜像uuid
    :param accessToken: access token
    :param kwargs: limit:
                   offset:
                   keyword: xxx
    :return:
    """
    content = get_utils(accessToken).cloud_http_request.get(CloudResourcesUrls.getMirror.value,
                                                            {
                                                                'offset': kwargs.get('offset', OFFSET),
                                                                'limit': kwargs.get('limit', LIMIT),
                                                                'keyword': kwargs.get('keyword', '')
                                                            })
    if mirrorId:
        total = content.get('total', 0)
        content = get_utils(accessToken).cloud_http_request.get(
            CloudResourcesUrls.getMirror.value, {'limit': total, 'offset': OFFSET})
        content = _getDetail(content, mirrorId, 'mirrorid')
    return content


def createMirror(accessToken):
    mirror_utils = get_utils(accessToken)


def createMirrorByUrl(accessToken):
    mirror_utils = get_utils(accessToken)


def deleteMirror(accessToken, mirrorIds):
    """
    删除镜像
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2104
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorIds
    return mirrorUtils(accessToken=accessToken).cloud_http_request.post(CloudResourcesUrls.deleteMirror.value,
                                                                        data=data)


def updateMirror(accessToken, mirrorId, mName, biosModel, mType, architecture, **kwargs):
    """
    更新镜像
    :param accessToken:
    :param mirrorId: 镜像uuid
    :param mName: 镜像名称
    :param biosModel: BIOS模式（Legacy|UEFI）
    :param mType: 镜像类型 (1: 系统镜像, 2: 云盘镜像 3: 应用镜像)
    :param architecture: 床铺架构
    :param kwargs:
                osName: 操作系统名称（镜像类型=1必填）
                osVersion: 操作系统版本（镜像类型=1必填）
                remark: xxx
    :return:
    """
    mirror_utils = get_utils(accessToken)

    mirror = getMirror(accessToken=accessToken, mirrorId=mirrorId).get('obj', None)
    if not mirror:
        raise KuberCloudException('params error', 'mirror [{}] not exist'.format(mirrorId))
    operationType = 2111
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['mirrorid'] = mirrorId
    data['mname'] = mName
    data['biosmodel'] = biosModel
    data['mtype'] = mType
    data['architecture'] = architecture

    if mType == 1:
        if not kwargs.get('osName') or not kwargs.get('osVersion'):
            raise KuberCloudException('params error', 'Invalid')
        data['osname'] = kwargs.get('osName')
        data['osversion'] = kwargs.get('osVersion')

    data['remark'] = kwargs.get('remark', mirror['remark'])

    return mirror_utils.cloud_http_request.post(CloudResourcesUrls.updateMirror.value, data=data)


def startMirror(accessToken, mirrorIds):
    """
    启用镜像
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2102
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorIds
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.startMirror.value, data=data)


def stopMirror(accessToken, mirrorIds):
    """
    停用镜像
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2103
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorIds
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.stopMirror.value, data=data)


def syncMirror(accessToken, mirrorId, mirrorServerId):
    """
    同步镜像
    :param accessToken: access token
    :param mirrorId: 镜像uuid
    :param mirrorServerId: 镜像服务器UUID
    :return:
    """
    operationType = 2105
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorServerId
    data['mirrorid'] = mirrorId
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.syncMirror.value, data=data)


def globalShareMirror(accessToken, mirrorIds):
    """
    镜像全局共享
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2109
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorIds
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.globalShareMirror.value, data=data)


def globalRecallMirror(accessToken, mirrorIds):
    """
    镜像全局召回
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2110
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    data['ids'] = mirrorIds
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.globalRecallMirror.value, data=data)


def getMirrorOwner(accessToken, mirrorId):
    """
    获取可更换所有者列表
    :param accessToken: access token
    :param mirrorId: 镜像uuid
    :return:
    """
    params = {'mirrorid': mirrorId, 'admintype': 1}
    return get_utils(accessToken).cloud_http_request.post(CloudResourcesUrls.getMirrorOwner.value, params=params)


def changeMirrorOwner(accessToken, mirrorId, ownerType):
    """
    更换镜像所有者
    :param accessToken: access token
    :param mirrorId: 镜像uuid
    :param ownerType: 所有者类型, 1:系统管理员 3:项目
    :return:
    """
    operationType = 2108
    data = _getOperationType(operationType, AsyncType.SYNC.value)
    params = {'mirrorid': mirrorId, 'type': ownerType}
    zone_utils = get_utils(accessToken)
    return zone_utils.cloud_http_request.post(CloudResourcesUrls.changeMirrorOwner.value, params=params, data=data)


def exportMirror(accessToken, mirrorIds):
    """
    导出镜像
    :param accessToken: access token
    :param mirrorIds: 镜像uuid (多个使用英文逗号分割)
    :return:
    """
    operationType = 2106
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['ids'] = mirrorIds
    return mirrorUtils(accessToken=accessToken).cloud_http_request.post(CloudResourcesUrls.exportMirror.value,
                                                                        data=data)


def downloadMirror(accessToken, mirrorId, userId):
    """
    下载镜像
    :param accessToken: access token
    :param mirrorId: 镜像uuid
    :param userId: 用户uuid
    :return:
    """
    mirror = getMirror(accessToken, mirrorId=mirrorId).get('obj', None)
    if not mirror:
        raise KuberCloudException('params error', 'mirror not exist')
    if mirror.get('downstate') == 0:
        raise KuberCloudException('params error', 'please export mirror first')
    if mirror.get('downstate') == 1:
        raise KuberCloudException('params error', 'please wait mirror export ended')
    if mirror.get('downstate') != 2 or not mirror.get('downpath'):
        raise KuberCloudException('params error', 'please export mirror first')
    params = {'mirrorid': mirrorId, 'userId': userId, 'type': 1}
    mirrorUtils(accessToken=accessToken).cloud_http_request.get(CloudResourcesUrls.downloadMirror.value, params)


def getMountableIso(accessToken, vmId, mirrorId=None, **kwargs):
    """
    查找可挂载至光驱的iso文件列表
    :param accessToken:
    :param vmId: 云主机UUID
    :param mirrorId: 镜像ID
    :param kwargs: limit:
                   offset:
                   keyword: xxx
    :return:
    """
    return get_utils(accessToken).cloud_http_request.get(CloudResourcesUrls.getMountableIso.value,
                                                         {
                                                             'vmid': vmId,
                                                             'status': 1,
                                                             'mformat': 'iso',
                                                             'mirrorid': mirrorId if mirrorId else '',
                                                             'offset': kwargs.get('offset', OFFSET),
                                                             'limit': kwargs.get('limit', LIMIT),
                                                             'keyword': kwargs.get('keyword', '')
                                                         })


def getMirrorServer(accessToken, **kwargs):
    """
    获取镜像服务器列表
    :param accessToken: access token
    :param kwargs: limit:
                   offset:
                   keyword: xxx
    :return:
    """
    return get_utils(accessToken).cloud_http_request.get(CloudResourcesUrls.getMirrorServer.value,
                                                         {
                                                             'offset': kwargs.get('offset', OFFSET),
                                                             'limit': kwargs.get('limit', LIMIT),
                                                             'keyword': kwargs.get('keyword', '')
                                                         })
